package cn.pugle.mianshi.thread1To10;

import static cn.pugle.mianshi.thread1To10.Constant.MAX;

public class PrintToTen2 implements Runnable {
    private int count = 1;
    private final Object lock = new Object();

    @Override
    public void run() {
        System.out.println(Thread.currentThread() + " Hello World");

        Thread thread1 = new Thread(() -> {
            try {
                while (count <= MAX) {
                    synchronized (lock) {
                        if (count % 2 == 0) {
                            System.out.println(Thread.currentThread() + " " + count++);
                            lock.notify();
                            if (count <= MAX) {
                                lock.wait();
                            }
                        }
                    }
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        thread1.start();

        Thread thread2 = new Thread(() -> {
            try {
                while (count <= MAX) {
                    synchronized (lock) {
                        if (count % 2 == 1) {
                            System.out.println(Thread.currentThread() + " " + count++);
                            lock.notify();
                            if (count <= MAX) {
                                lock.wait();
                            }
                        }
                    }
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        thread2.start();

        try {
            thread1.join();
            thread2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        new PrintToTen2().run();
    }
}
